<template>
  <m-window-frame
    :title="$t('下载')"
    style="height: 100%"
    :okLoading="saveLoading"
    :ok-text="$t('下 载')"
    :cancel-text="$t('关 闭')"
    class="v-201-download"
    @cancel="handleCancel"
    @ok="handleSave"
  >
    <div class="download-201-container">
      <el-form
        ref="ruleFormRef"
        :rules="rules"
        :model="form"
        label-width="85px"
        :hide-required-asterisk="true"
      >
        <el-form-item
          :label="$t('选择项目')"
          prop="project"
        >
          <el-row :gutter="12">
            <el-col :span="24">
              <el-select
                v-model="form.project"
                :suffix-icon="SelectSuffix"
              >
                <el-option
                  v-for="item in projectList"
                  :key="item.guid"
                  :label="item.name"
                  :value="item.guid"
                ></el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item
          :label="$t('选择项目版本')"
          prop="projectVersion"
        >
          <el-row :gutter="12">
            <el-col :span="24">
              <el-select
                v-model="form.projectVersion"
                :suffix-icon="SelectSuffix"
              >
                <el-option
                  v-for="item in projectVersionList"
                  :key="item.id"
                  :label="item.version"
                  :value="item.version"
                ></el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item
          :label="$t('下载目录')"
          prop="filePath"
        >
          <el-row :gutter="12">
            <el-col
              :span="24"
              class="interface-path-box"
            >
              <el-input v-model="form.filePath"></el-input>
              <img
                src="statics/icons/app/iconmore.png"
                class="_btn"
                @click="changePath"
              />
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </div>
  </m-window-frame>
</template>
<script lang="ts" setup>
import MWindowFrame from "@/common/ipcWindow/WindowFrame.vue";
import { ref, watch, reactive, onBeforeMount } from "vue";
import { CloseData } from "./index";
import type { FormInstance, FormRules } from "element-plus";
import { ipcWindowUtil } from "@/mdesign-lib/mdesign-app.umd.js";
import { locale } from "@/mdesign-lib/mdesign-app.umd.js";
import { ipcRenderer } from "electron";
import { IpcMsg } from "@/mdesign-lib/mdesign-main.js";
import SelectSuffix from "@/modules/model/comps/common/SelectSuffix.vue";
import { localFile } from "@/mdesign-lib/mdesign-app.umd.js";
import { archService } from "@/mdesign-lib/mdesign-app.umd.js";

ipcRenderer.on(IpcMsg.WindowAbort, () => (saveLoading.value = false));

interface ProjectItem {
  guid: string;
  name: string;
  code: string;
  prjSecurityLevel: string;
}

interface ProjectVersionItem {
  id: string;
  currentFlag: number;
  dataUuid: string;
  prjGuid: string;
  srcTool: string;
  status: string;
  version: string;
}

const form = reactive<Record<string, any>>({
  project: "",
  projectVersion: "",
  filePath: ""
});

const rules = reactive<FormRules>({
  project: [
    {
      required: true,
      validator: (rule, value: string, cb) => {
        if (!value) {
          return cb(new Error(locale.t("请选择项目")));
        } else {
          cb();
        }
      }
    }
  ],
  // projectVersion: [
  //   { required: true, validator: (rule, value: string, cb) => {
  //     if (!form.project) {
  //       return cb(new Error(locale.t('请先选择项目')));
  //     }
  //     if (!value) {
  //       return cb(new Error(locale.t('请选择项目版本')));
  //     } else {
  //       cb();
  //     }
  //   } }
  // ],
  filePath: [{ required: true, trigger: "change", message: "请选择下载目录" }]
});

const saveLoading = ref(false);
const ruleFormRef = ref<FormInstance>();
// const route = useRoute();
const projectList = ref<ProjectItem[]>([]);
const projectVersionList = ref<ProjectVersionItem[]>([]);

// watch(
//   () => route.fullPath,
//   () => {
//     const routeQuery = route.query as unknown;
//   },
//   { immediate: true }
// );

onBeforeMount(() => {
  getProjectList();
});

const getProjectList = async () => {
  projectList.value = await archService.get201ProjectList();
};

watch(
  () => form.project,
  projectGuid => {
    if (projectGuid) {
      form.projectVersion = "";
      getProjectVersionList(projectGuid);
    }
  }
);

const getProjectVersionList = async (projectGuid: string) => {
  projectVersionList.value = await archService.get201ProjectVersionList(projectGuid);
};

const changePath = async () => {
  const chooseFilePathResult = await localFile.chooseSaveFilePath({
    title: "选择下载目录",
    defaultPath: "Untitled.md3",
    filters: [
      {
        name: "md3",
        extensions: ["md3"]
      }
    ]
  });
  const filePath = chooseFilePathResult.filePath;
  if (chooseFilePathResult.canceled || !filePath) return;
  form.filePath = filePath;
};

const handleSave = async () => {
  if (!ruleFormRef.value) return;
  const valid = await ruleFormRef.value.validate().catch(() => false);
  if (!valid) return;
  saveLoading.value = true;
  const info = {
    prjGuid: form.project,
    srcTool: "march",
    filePath: form.filePath
  };
  if (form.projectVersion) {
    Object.assign(info, { nodeVersion: form.projectVersion });
  }
  ipcWindowUtil.sendWindowChange({ success: true, info });
};

function handleclose(data: CloseData) {
  saveLoading.value = false;
  ipcWindowUtil.closeWindow(data);
}
function handleCancel() {
  handleclose({ success: false });
}
</script>
<style lang="scss">
body .el-select-dropdown .el-select-dropdown__list {
  max-height: 150px;
}
.v-201-download {
  flex: 1;
  display: flex;
  overflow: hidden;
  .download-201-container {
    flex: 1;
    overflow: hidden;
    padding: 32px;
    .el-form-item {
      height: 32px;
      margin-bottom: 14px;
      .el-form-item__label {
        line-height: 32px;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
      }
      .el-input__wrapper {
        border: 1px solid rgba(0, 0, 0, 0.15);
        box-shadow: none;
        input {
          height: 24px;
        }
      }
      .el-select {
        width: 100%;
        .el-select__wrapper {
          border: 1px solid rgba(0, 0, 0, 0.15);
          box-shadow: none;
          border-radius: 0;
          height: 28px;
          .el-select__icon {
            transition: none;
          }
        }
        .el-select__icon {
          width: 20px;
        }
      }
      .el-button {
        border-color: rgba(0, 0, 0, 0.15);
        padding: 8px;
        border-radius: 0;
        &:hover {
          border-color: var(--md-primary-color);
        }
      }
      .ownerBox {
        height: 28px;
        border: 1px solid rgba(0, 0, 0, 0.15);
        position: relative;
        padding-left: 7px;
        padding-right: 34px;
        ._btn {
          position: absolute;
          display: inline-block;
          cursor: pointer;
          top: 50%;
          right: 7px;
          transform: translateY(-50%);
        }
      }
    }

    .el-row {
      width: 100%;
      .el-col {
        min-height: 32px;
        display: flex;
        align-items: center;
      }
    }
    .interface-path-box {
      position: relative;
      .el-input__wrapper {
        padding-right: 34px;
      }
      ._btn {
        position: absolute;
        display: inline-block;
        cursor: pointer;
        top: 50%;
        right: 14px;
        transform: translateY(-50%);
      }
    }
  }
}
</style>
